package main

import (
	database "goproject/post/database/grom"
	handler "goproject/post/handler/gin"
	util "goproject/post/utils"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/gin-gonic/gin"
)

func Init() {
	util.InitSlog("./logs/post.log")
	database.ConnectPostDB("./conf", "db", util.YAML, "./logs")
}

func ListenTermSignal() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM) //注册信号2和15。Ctrl+C对应SIGINT信号
	sig := <-c                                        //阻塞，直到信号的到来
	slog.Info("receive term signal " + sig.String() + ", going to exit")
	database.ClosePostDB() //关闭数据库连接
	os.Exit(0)             //进程退出
}

func main() {
	Init()
	go ListenTermSignal()
	engine := gin.Default()
	// 修改静态资源不需要重启GIN，刷新页面即可
	engine.Static("/js", "views/js") //在url是访问目录/js相当于访问文件系统中的views/js目录
	engine.Static("/css", "views/css")
	engine.StaticFile("/favicon.ico", "views/img/dqq.png") //在url中访问文件/favicon.ico，相当于访问文件系统中的views/img/dqq.png文件
	engine.LoadHTMLGlob("views/html/*")

	engine.GET("/login", func(ctx *gin.Context) { ctx.HTML(http.StatusOK, "login.html", nil) })
	engine.GET("/regist", func(ctx *gin.Context) { ctx.HTML(http.StatusOK, "user_regist.html", nil) })
	engine.GET("/modify_pass", handler.Auth, func(ctx *gin.Context) { ctx.HTML(http.StatusOK, "update_pass.html", nil) })
	engine.POST("/login/submit", handler.Login)
	engine.POST("/regist/submit", handler.RegistUser)
	engine.POST("/modify_pass/submit", handler.Auth, handler.UpdatePassword)
	engine.GET("/logout", handler.Logout)

	// 新闻相关的路由
	group := engine.Group("/news")
	group.GET("", handler.NewsList)
	group.GET("/issue", func(ctx *gin.Context) { ctx.HTML(http.StatusOK, "news_issue.html", nil) })
	group.POST("/issue/submit", handler.Auth, handler.PostNews)
	group.GET("/belong", handler.NewsBelong)
	group.GET("/:id", handler.GetNewsById)
	group.GET("/delete/:id", handler.Auth, handler.DeleteNews)
	group.POST("/update", handler.Auth, handler.UpdateNews)

	engine.GET("", func(ctx *gin.Context) { ctx.Redirect(http.StatusMovedPermanently, "news") }) //新闻列表页是默认的首页
	engine.Run("127.0.0.1:5678")
}
